package com.kay.server;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.OutputStream;

/**
 * @Description:
 * @Author: Kay
 * @CreateDate: 2021/8/3$ 10:29$
 * @UpdateUser: Kay
 * @UpdateDate: 2021/8/3$ 10:29$
 */
public class Response {
    private OutputStream outputStream;

    public OutputStream getOutputStream() {
        return outputStream;
    }

    public void setOutputStream(OutputStream outputStream) {
        this.outputStream = outputStream;
    }

    public Response(OutputStream outputStream) {
        this.outputStream = outputStream;
    }

    public Response() {
    }

    public void outputStaticResourcesByAbsolutePath(String absolutePath) throws IOException {
        File file = new File(absolutePath);
        if (file.exists() && file.isFile()) {  // file存在，并且是文件形式
            StaticResourcesUtil.outputStaticResource(new FileInputStream(file), outputStream);
        } else {
            // 静态资源不存在，直接输出404
            outputContent(HttpProtocolUtils.getContent404());
        }
    }

    /**
     * 输出静态资源
     */
    public void outputStaticResources(String path) throws IOException {
        String absolutePath = StaticResourcesUtil.getAbsolutePath(path);
        System.out.println(" _____________ absolutePath : " + absolutePath);

        File file = new File(absolutePath);
        if (file.exists() && file.isFile()) {  // file存在，并且是文件形式
            StaticResourcesUtil.outputStaticResource(new FileInputStream(file), outputStream);
        } else {
            // 静态资源不存在，直接输出404
            outputContent(HttpProtocolUtils.getContent404());
        }
    }

    /**
     * 通过OutputStream向页面输出内容
     *
     * @param content
     */
    public void outputContent(String content) throws IOException {
        outputStream.write(content.getBytes());
    }
}
